package com.chainyoung.component_tmperson.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.CommonList;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.common_widget.loadsir.callback.Callback;
import com.chainyoung.common.common_widget.loadsir.core.LoadService;
import com.chainyoung.common.common_widget.loadsir.core.LoadSir;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.custom_widget.EmptyCallback;
import com.chainyoung.common.custom_widget.LoadingCallback;
import com.chainyoung.common.custom_widget.RetryCallback;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonFragmentComponent;
import com.chainyoung.component_tmperson.di.module.PersonFragmentModule;
import com.chainyoung.component_tmperson.entity.MyTotalAsset;
import com.chainyoung.component_tmperson.entity.Purse;
import com.chainyoung.component_tmperson.ui.activity.cloudwallet.SelectCoinTypeActivity;
import com.chainyoung.component_tmperson.ui.adapter.WalletAdapter;
import com.chainyoung.component_tmperson.ui.mvp.contract.WalletContact;
import com.chainyoung.component_tmperson.ui.mvp.presenter.WalletPresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chainyoung.common.event.BaseEvent.EventCode.REFRESH_TOTAL_ASSET;
import static com.chainyoung.component_tmperson.ui.fragment.MyPurseAddrListFragment.TYPE_CLOUD;
import static com.chainyoung.component_tmperson.ui.fragment.MyPurseAddrListFragment.TYPE_LOCAl;


public class WalletCloudListFragment extends BaseFragment<WalletPresenter> implements WalletContact.View {


    @BindView(R2.id.txt_asset_title)
    TextView txtAssetTitle;
    @BindView(R2.id.tv_asset_total)
    TextView tvAssetTotal;
    @BindView(R2.id.rv_list)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;


    private WalletAdapter walletAdapter;
    private List<Purse> mData = new ArrayList<>();
    private LoadService loadService;

    /**
     * 云端总资产
     */
    private String totalAsset = "0";

    /**
     * 资产是否可见
     */
    private boolean isVisible = true;


    public static WalletCloudListFragment newInstance(boolean isVisible) {
        WalletCloudListFragment fragment = new WalletCloudListFragment();
        Bundle args = new Bundle();
        args.putBoolean("isVisible", isVisible);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            isVisible = getArguments().getBoolean("isVisible");
        }

    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPersonFragmentComponent.builder()
                .appComponent(appComponent)
                .personFragmentModule(new PersonFragmentModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initUi() {
        super.initUi();
        initRecyclerView();
        initLoadSir();
    }

//    @Override
//    protected boolean useLoadSir() {
//        return true;
//    }
//
//    @Override
//    protected void onPageRetry(View v) {
//        loadData();
//    }

    private void initLoadSir() {
        LoadSir loadSir = new LoadSir.Builder()
                .addCallback(new LoadingCallback())
                .addCallback(new EmptyCallback())
                .addCallback(new RetryCallback())
                .setDefaultCallback(LoadingCallback.class)
                .build();
        loadService = loadSir.register(recyclerView, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadService.showCallback(LoadingCallback.class);
                loadData();
            }
        });
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_gray));
        recyclerView.addItemDecoration(itemDecoration);
        walletAdapter = new WalletAdapter(mData);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(walletAdapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });

    }


    @Override
    protected void initData() {

    }


    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_fragment_wallet_cloud_list;
    }


    @OnClick(R2.id.iv_add_wallet)
    void selectCoin() {
        Intent intent = new Intent(mContext, SelectCoinTypeActivity.class);
        intent.putExtra("walletType", TYPE_CLOUD);
        intent.putExtra("isImportWallet", false);
        mContext.startActivity(intent);
    }


    @Override
    protected void onFirstUserVisible() {
        loadData();
    }

    @Override
    public void onUserVisible() {
        super.onUserVisible();
        loadData();
    }

    private void setVisibleView() {
        tvAssetTotal.setText(isVisible ? "CNY " + totalAsset : "CNY ****");
        walletAdapter.setShowAsset(isVisible);
        walletAdapter.notifyDataSetChanged();
    }


    private void loadData() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        mPresenter.getMyPurse(map);
        TreeMap<String, Object> map1 = new TreeMap<>();
        map1.put("token", SPUtil.getString(LibConstant.TOKEN));
        mPresenter.getMyTotalAsset(map1);

    }


    @Override
    public void onGetMyPurseSuccess(CommonList<Purse> data) {
        refreshLayout.finishRefresh();
        mData.clear();
        if (data == null) {
            loadService.showCallback(EmptyCallback.class);
            //showPageEmpty();
            return;

        }
        mData.addAll(data.getList());
        walletAdapter.notifyDataSetChanged();
        if (mData.isEmpty()) {
            //showPageEmpty();
            loadService.showCallback(EmptyCallback.class);
        } else {
            //showPageContent();
            loadService.showSuccess();
        }
        setVisibleView();
    }

    @Override
    public void onGetMyPurseFailed() {
        //  showPageError();
        loadService.showCallback(RetryCallback.class);
    }

    @Override
    public void onGetTotalAsset(MyTotalAsset data) {
        totalAsset = String.valueOf(new BigDecimal(data.getTotal_cny()).setScale(2, BigDecimal.ROUND_DOWN));
        tvAssetTotal.setText(String.format("%s", "CNY " + totalAsset));
        setVisibleView();
        EventBus.getDefault().post(new BaseEvent<>(REFRESH_TOTAL_ASSET));
    }

    public String getTotalAsset() {
        return totalAsset;
    }

    @Subscriber
    void setAssetVisible(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.IS_ASSET_VISIBLE) {
            isVisible = (boolean) event.getData();
            setVisibleView();
        }
    }
}
